<template>
  <el-dialog title="选择商品" :visible.sync="dialogVisible" :close-on-click-modal="false">
    <div class="content" @click.stop="()=>{}">
      <el-form label-position="left" label-width="100px" style="width: 100%; padding-left: 20px;">
        <el-form-item label="所选商品：" v-if="config.count !== 1">
          <div class="el-tag-box">
              <el-tag v-for="(item, index) of result" :key="item.goodsId" :closable="true" @close="delItem(index)">{{item.name}}</el-tag>
          </div>
        </el-form-item>
      </el-form>
      <el-form ref="searchForm" class="search-block" :model="listQuery" label-position="right" label-width="100px" style="width: 100%">
        <el-row>
          <el-col :md="24" :lg="12" :xl="8">
            <el-form-item label="商品分类：" prop="categoryId">
              <el-select v-model="listQuery.categoryId" :loading="categoryLoading" placeholder="请选择" clearable>
                <el-option v-for="(item, index) of categoryTree" :style="{paddingLeft: `${item._level * 15}px`}" :key="index" :label="`${item.parentId ? '∟' : ''}${item.name}`" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="24" :lg="12" :xl="8">
            <el-form-item label="商品款号：" prop="serialNo">
              <el-input @keyup.enter.native="search" v-model="listQuery.serialNo" placeholder="商品款号" maxlength="50" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="24" :lg="12" :xl="8">
            <el-form-item label="商品名称：" prop="name">
              <el-input @keyup.enter.native="search" v-model="listQuery.name" placeholder="商品名称" maxlength="50" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="24" :lg="12" :xl="8">
            <el-form-item label="是否售卖：" prop="isSell">
              <el-select v-model="listQuery.isSell">
                <el-option label="全部" :value="''"></el-option>
                <el-option label="是" :value="1"></el-option>
                <el-option label="否" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="24" :lg="12" :xl="8">
            <el-form-item label="渠道类型：" prop="businessModel">
              <el-select v-model="listQuery.businessModel">
                <el-option label="全部" :value="''"></el-option>
                <el-option label="自营" :value="1"></el-option>
                <el-option label="招商" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="24" :lg="12" :xl="8" v-if="listQuery.businessModel!==1">
            <el-form-item label="供应商：" prop="merchantId">
              <el-select v-model="listQuery.merchantId" placeholder="请选择" filterable clearable>
                <el-option v-for="item in merchants" :key="item.supplyCode" :label="item.supplyName" :value="item.supplyCode"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="" class="btn-item">
          <el-button type="primary" size="mini" icon="el-icon-search" plain @click="search">搜索</el-button>
          <span class="btn-reset"  @click="resetForm('searchForm')">清空搜索条件</span>
        </el-form-item>
      </el-form>
      <div class="check-all">
        <label class="input-checkbox" v-if="config.count !== 1">
          <input type="checkbox" :value="checkAll" v-model="checkAll" @change="handleCheckAll"/>
          <span></span>
        </label>
      </div>
      <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border @row-click="clickRow">
          <el-table-column align="center" width="50">
              <template slot-scope="scope">
                  <label class="input-radio" v-if="config.count === 1">
                      <input type="radio" :value="{goodsId: scope.row.goodsId}" v-model="itemsRadio" @change="(e) => setValue(e.target.checked, scope.row)"/>
                      <span></span>
                  </label>
                  <label class="input-checkbox" v-else>
                      <input type="checkbox" :value="{goodsId: scope.row.goodsId}" v-model="itemsCheck" @change="(e) => setValue(e.target.checked, scope.row)"/>
                      <span></span>
                  </label>
              </template>
          </el-table-column>
          <el-table-column align="center" label="款号" prop="serialNo" width="110"></el-table-column>
          <el-table-column align="center" label="商品名称" prop="name" min-width="110" show-overflow-tooltip></el-table-column>
          <!-- <el-table-column align="center" label="虚拟商品" width="100" v-if="!config.goodsType">
            <template slot-scope="scope">
              <span v-if="scope.row.goodsType===2" style="color: red">是</span>
              <span v-else>否</span>
            </template>
          </el-table-column> -->
          <el-table-column align="center" label="分类" prop="categoryName" min-width="60"></el-table-column>
          <el-table-column align="center" label="上架状态" width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.upshelf===1">已上架</span>
              <span v-else style="color: #bbb">已下架</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="是否售卖" width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.isSell===1">是</span>
              <span v-else style="color: #bbb">否</span>
            </template>
          </el-table-column>
      </el-table>
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="listQuery.pageIndex"
        :page-size="listQuery.pageSize"
        background
        layout="total, prev, pager, next, jumper"
        style="text-align: center"
        :total="listTotal">
      </el-pagination>
    </div>
    <div slot="footer" class="dialog-footer" @click.stop="()=>{}">
      <el-button type="primary" :loading="btnLoading" @click="choose">确定</el-button>
      <el-button @click="close">取消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getCategoryTree, getMerchantWarehouse} from '../../api/common'
import treeToArray from '@/components/TreeTable/eval'
export default {
  name: 'choose-goods',
  props: {
    config: { type: Object, default(){ return {} } },
    selected: { type: Array, default(){ return [] } },
  },
  data(){
    return {
      checkAll: false,
      dialogVisible: true,
      btnLoading: false,
      categoryLoading: true,
      result: this.selected,
      itemsCheck: this.selected.length ? this.selected.map(item => { return { goodsId: item.goodsId }}): [],
      itemsRadio: this.selected.length ? {goodsId: this.selected[0].goodsId} : {},
      merchants: [],
      categoryTree: [],
      listQuery: {
        categoryId: '',
        serialNo: '',
        name: '',
        isSell: '',
        businessModel: '',
        merchantId: '',
        excludeCrush: this.config.excludeCrush || 0,
        goodsType: this.config.goodsType || 1,
        pageIndex: 1,
        pageSize: 8
      },
      list: [],
      listTotal: 0,
      listLoading: false
    }
  },
  created(){
    this.getCategoryTree()
    this.getList()
    this.getMerchantWarehouseList()
  },
  methods: {
    copyObject (obj) {
      let newObj = {}
      if (obj instanceof  Array) {
        newObj = []
      }
      for (let key in obj) {
        let val = obj[key]
        newObj[key] = typeof val === 'object' ? this.copyObject(val) : val;
      }
      return newObj
    },
    handleCheckAll () {
      let temp = this.copyObject(this.list)
      if (this.checkAll) {
        this.itemsCheck.map((item, index) => {
          this.list.map((_item, _index) => {
            if (_item.goodsId === item.goodsId) {
              temp.splice(_index, 1)
            }
          })
        })
        let tempResult = temp
        let tempList = temp.map(item => { return { goodsId: item.goodsId }})
        this.itemsCheck = this.itemsCheck.concat(tempList)
        this.result = this.result.concat(tempResult)
      } else {
        if (this.itemsCheck.length === this.listQuery.pageSize) {
          this.itemsCheck = []
          this.result = []
        } else {
          // 将一个数组中的值从另一个数组剔除
          this.itemsCheck = this.itemsCheck.filter(item => {
            let idList= this.list.map(v => v.goodsId)
            return !idList.includes(item.goodsId)
          })
          this.result = this.result.filter(item => {
            let resultList= this.list.map(v => v.goodsId)
            return !resultList.includes(item.goodsId)
          })
        }
      }
    },
    // 获取列表
    getList () {
      this.listLoading = true;
      this.request({
        url: '/bsnl-product/goods/query',
        method: 'post',
        data: this.listQuery
      }).then(({data, totalCount}) => {
        this.list = data
        this.listTotal = totalCount
        this.listLoading = false
        let tempList = this.list.map(item => { return { goodsId: item.goodsId }})
        let index = this.itemsCheck.findIndex((item) => {
          return item.goodsId === tempList[0].goodsId
        })
        if (index >= 0 && tempList.length === this.listQuery.pageSize) {
          this.checkAll = true
        } else {
          this.checkAll = false
        }
      }).catch(err => {
        this.list = []
        this.listTotal = 0
        this.listLoading = false
      });
    },
    // 获取供应商、仓库列表
    getMerchantWarehouseList() {
      getMerchantWarehouse().then(({data}) => {
        this.merchants = data.viewList.filter(item => item.supplyCode !== null);
      });
    },
    // 获取分类树
    getCategoryTree() {
      getCategoryTree().then(({data}) => {
        let tmp = data ? data : [];
        this.categoryTree = treeToArray(tmp, {
          type: Boolean,
          default: false
        });
        this.categoryLoading = false
      }).catch(err => {
        this.categoryTree = [];
        this.categoryLoading = false
      });
    },
    resetForm (formName) {
      this.$nextTick(() => {
        this.$refs[formName].resetFields()
      })
    },
    // 搜索
    search () {
      this.listQuery.pageIndex = 1
      this.getList()
    },
    // 切换分页
    handleCurrentChange (page) {
      this.listQuery.pageIndex = page
      this.getList()
    },
    // 选择change
    setValue(checked, row){
      if(checked){
        if(this.config.count ===1 ){
          this.result = [row]
        } else {
          this.result.push({ ...row })
        }
      } else {
        let index = this.itemsCheck.findIndex(item => row.goodsId === item.goodsId);
        this.result.splice(index, 1);
      }
      let len = this.result.length
      if (len % this.listQuery.pageSize === 0) {
        this.checkAll = true
      } else {
        this.checkAll = false
      }
    },
    // 单击行
    clickRow(row) {
      if (this.config.count === 1) {
        this.itemsRadio = { goodsId: row.goodsId };
        this.result = [row];
      } else {
        let index = this.itemsCheck.findIndex(item => row.goodsId === item.goodsId);
        if (index < 0){
          this.itemsCheck.push({ goodsId: row.goodsId });
          this.result.push({ ...row });
        } else {
          this.itemsCheck.splice(index, 1);
          this.result.splice(index, 1);
        }
      }
      let len = this.itemsCheck.length
      if (len % this.listQuery.pageSize === 0) {
        this.checkAll = true
      } else {
        this.checkAll = false
      }
    },
    // 通过tag删除
    delItem(index) {
      this.itemsCheck.splice(index, 1);
      this.result.splice(index, 1);
    },
    // 关闭弹窗
    close(){
      this.dialogVisible = false;
      document.body.removeChild(this.$el);
    },
    // 选完，点击确定
    choose(){
      // 涉及到需要返回一级类目的功能，请勿注释，否则可能会导致线上bug
      if(!this.categoryTree.length) {
        this.$message({
          type: 'error',
          message: '商品类别还在加载，请稍等几秒重试'
        })
        return
      }
      if(this.result.length < 1){
        return this.$message.error('请选择商品');
      }
      if(this.config.count > 0 && this.itemsCheck.length > this.config.count){
        return this.$message.error(`最多选择${this.config.count}个商品`);
      }

      let id = ''
      let type = 0
      let name = ''
      // 返回一级分类id及其名称
      this.categoryTree.forEach(item => {
        // 当id相等
        this.result.map(i => {
          if(i.categoryId === item.id){
            if (item.parentId === 0) {
              id = item.id
              this.categoryTree.forEach(async it => {
                if(it.id === id) {
                  name = it.name
                }
              })
              i.parentCategoryId = id
              i.parentCategoryName = name
            } else {
              id = item.parentId
              this.categoryTree.forEach(async it => {
                if(it.id === id) {
                  name = it.name
                }
              })
              i.parentCategoryId = id
              i.parentCategoryName = name
            }
          }
          return i
        })
        // if(this.result[0].categoryId === item.id) {
        //   console.log('target', item)
        //   // 父id为0 则为一级分类
        //   if (item.parentId === 0) {
        //     id = item.id
        //   } else {
        //     id = item.parentId
        //     type = 1
        //   }
        // }
      })
      // if(type) {
      //   this.categoryTree.map(item => {
      //     if(item.id === id) {
      //       name = item.name
      //     }
      //   })
      // }
      // this.result[0].parentCategoryId = id
      // this.result[0].parentCategoryName = name
      this.$emit('choose', this.result);
      this.close();
    }
  }
}
</script>
<style lang="scss" scoped>
.check-all {
  margin-left: 15px;
  margin-top: 16px;
  position: absolute;
  z-index: 99;
}
</style>